﻿using Microsoft.SharePoint;
using System;
using System.Collections.Generic;

namespace SP.FeatureAdministrationTool.SiteModule
{
    public class SiteManager
    {
        public static List<Site> GetSites(Guid siteCollectionId)
        {
            List<Site> sites = new List<Site>();
            using (SPSite siteCollection = new SPSite(siteCollectionId))
            {
                BuildSubWebTree(siteCollection.RootWeb, 0, sites);
            }

            return sites;
        }

        private static void BuildSubWebTree(SPWeb web, int level, List<Site> sites)
        {
            string title = string.Format("{0} ({1})", web.Title, web.ID.ToString());
            title = title.PadLeft(title.Length + level * 2, '-');
            sites.Add(new Site()
            {
                Title = title,
                Id = web.ID
            });

            try
            {
                if (web.Webs.Count > 0)
                {
                    foreach (SPWeb subWeb in web.Webs)
                    {
                        BuildSubWebTree(subWeb, level + 1, sites);
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
            }
        }
    }
}
